<?php
namespace Home\Model;

use  Think\Model;

class UsersModel extends Model
{
  protected $autoCheckFields =false;

  public function check_token($token)
  {
    //expire_time过期暂时不判断
    $map = array('token' => $token);
    $field = "id as user_id, nickname, openid, shop_id, phone, types, xcx_openid, app_id";//expire_time
    $user = M("users")->field($field)->where($map)->find();

    if (!$user) {
      return false;
    }

    //检测商户是否停用
    if ($user['types'] == 1) {
      //$user['user_id'] 应该有值 怎么报错？
      $map = array('user_id' => $user['user_id']);
      $status = M("shops")->where($map)->getField("status");
      if ($status == 2) {
        return false;
      }
    }

    return $user;
  }

  public function create_token($user_id)
  {
    $user = M('users')->where("id=$user_id")->find();

    if ($user) {
      $now = gmtime();
      if ($user['expire_time'] - $now < 5 * 60 && $user['token']) {
        return $user['token'];
      } else {
        $data['token'] = md5($user_id.randomFromDev(16));
        $data['expire_time'] = gmtime() + 5 * 60;
        M("users")->where("id=$user_id")->save($data);

        return $data['token'];
      }
    }

    return false;
  }
}
